package com.scsystem.xysc.aop;

import cn.hutool.json.JSONUtil;
import com.scsystem.xysc.mapper.ActionLogMapper;
import com.scsystem.xysc.pojo.ActionLog;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class LogAOP {

    @Resource
    private ActionLogMapper actionLogMapper;

    @Pointcut("@annotation(com.scsystem.xysc.aop.LogOperations)")
    public void pt() {}

    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) {

        //创建日志记录对象
        ActionLog actionLog = new ActionLog();

        //日志类型
        actionLog.setLogType("info");
        //记录时间
        actionLog.setActionTime(LocalDateTime.now());
        //日志信息
        String i = ""; /*"全限定类名：" + joinPoint.getTarget().getClass().getName();*/

        Object proceed = null;
        try {
            //开始时间（毫秒）
            long start = System.currentTimeMillis();
            proceed = joinPoint.proceed();
            long time = System.currentTimeMillis() - start;
            actionLog.setTimeConsuming(time);
        } catch (Throwable e) {
            i = i + "，错误信息：" + e.getMessage();
            log.error("操作失败：{}", e.getMessage());
            actionLog.setLogType("error");
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogOperations annotation = method.getAnnotation(LogOperations.class);

        //操作描述
        actionLog.setOperationDescription("模块名：" + annotation.module() + "，操作描述：" + annotation.operation());

        if ((RequestContextHolder.getRequestAttributes()) instanceof ServletRequestAttributes) {

            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            HttpSession session = request.getSession();
            //请求的URL
            actionLog.setUrl(String.valueOf(request.getRequestURL()));
            //发起请求的用户或管理员的id
            if (session.getAttribute("userId") != null && session.getAttribute(("userType")) != null) {
                actionLog.setActionId((long) session.getAttribute("userId"));
                //发起请求的用户类别（管理员，普通用户，商家）
                actionLog.setUserType((String) session.getAttribute(("userType")));
            }

            i = i + "，方法名：" + method.getName();
            actionLog.setParameter(JSONUtil.toJsonStr(joinPoint.getArgs()));
            if (proceed != null) {
                actionLog.setResult(proceed.toString());
            }
            actionLog.setIpaddr(request.getRemoteAddr());
        }



        actionLog.setMessage(i);

        actionLogMapper.insert(actionLog);
        return proceed;
    }
}
